<template>
  <div>
    <a-space>
      <a-select
        v-for="level in props.level || 4"
        :key="level"
        v-model="targetData.city[level - 1].id"
        :style="{ width: props.width || '120px' }"
        :placeholder="targetData.city[level - 1].label"
        :loading="targetData.city[level - 1].loading"
        @change="changeCity(targetData.city[level - 1])"
      >
        <a-option
          v-for="(item, index) in targetData.city[level - 1].value"
          :key="index"
          :value="item.id"
          >{{ item.name }}</a-option
        >
      </a-select>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
  import { getChildRegion } from '@/api/common';
  import { onMounted, reactive } from 'vue';

  interface CityRule {
    city: Array<{
      label: string;
      value: Array<any>;
      id: string | number;
      type: string;
      loading: boolean;
      address: string;
      center: string;
    }>;
  }

  const targetData = reactive<CityRule>({
    city: [
      {
        label: '省',
        value: [],
        type: 'province',
        id: '',
        address: '',
        loading: false,
        center: '',
      },
      {
        label: '市',
        value: [],
        type: 'city',
        id: '',
        address: '',
        loading: false,
        center: '',
      },
      {
        label: '区',
        value: [],
        type: 'area',
        id: '',
        address: '',
        loading: false,
        center: '',
      },
      {
        label: '街道',
        value: [],
        type: 'street',
        id: '',
        address: '',
        loading: false,
        center: '',
      },
    ],
  });
  const emit = defineEmits<{ (e: 'callback', obj: object): void }>();
  const props = defineProps<{
    level?: number;
    width?: string | number;
    ids: any;
    address: any;
  }>();
  // 渲染city
  const renderCity = async (id: string | number = 0, type: string) => {
    if (type) {
      const target = targetData.city.find((item) => {
        return item.type == type;
      });
      if (target?.loading) target.loading = true;
      // target!.loading = true;
      const res = await getChildRegion(id);
      targetData.city.forEach((item) => {
        if (item.type == type && res.data && res.data.result && res.data.result.length) {
          item.value = res.data.result;
        }
      });
      if (target?.loading) target.loading = false;
      // target!.loading = false;
    }
  };

  // 选择城市之后进行回调操作
  const changeCity = (val: Record<string, any>) => {
    // 看下当前选择城市的索引
    const cityIndex = targetData.city.findIndex((city) => {
      return val.type == city.type;
    });
    const cityData = targetData.city[cityIndex];
    targetData.city[cityIndex].address = targetData.city[cityIndex].value.find(
      (item: Record<string, any>) => item.id == val.id
    )?.name;
    targetData.city[cityIndex].center = targetData.city[cityIndex].value.find(
      (item: Record<string, any>) => item.id == val.id
    )?.center;


    //  得出索引之后将大于它的索引的item设置为空
    targetData.city.forEach((item, index) => {
      if (index > cityIndex) {
        item.value = [];
        item.id = '';
      }
    });

    // 如果是最后一项 回调出去
    // if (cityIndex + 1 == (props.level || 4)) {
      const cityName: string[] = [];
      const cityId: (string | number)[] = [];
      const cityCenter: string[] = [];
      const cityWay = targetData.city.map((item) => {
        cityName.push(item.address);
        cityId.push(item.id);
        cityCenter.push(item.center);
        return {
          id: item.id,
          name: item.address,
          center: item.center,
        };
      });
      const cityRes = {
        ids: cityId,
        cities: cityName,
        center: cityCenter,
        values: cityWay,
      };
      emit('callback', cityRes);
    // }

    renderCity(cityData.id, targetData.city[cityIndex + 1].type);

  };

  // 初始化city
  const init = () => {
    // if (!props?.ids) renderCity(0, 'province');
    renderCity(0, 'province');
    if (props.ids) {
      const cityData = ['province', 'city', 'area', 'street', ''];
      const ids = props.ids.split(',');
      const address = props.address.split(',');
      targetData.city = targetData.city.map((item, index) => {
        item.id = ids[index];
        item.address = address[index];
        renderCity(item.id, cityData[index + 1]);
        return item;
      });
    }
  };

  onMounted(() => {
    init();
  });
</script>
